import pandas as pd  
from sqlalchemy import create_engine  

postgres_host = "172.16.137.39"
postgres_port = "5432"
postgres_user = "a2513220218"
postgres_password = "xawl-6043"
postgres_database = "a2513220218"

csv_file_path = "D:\数据库\实验报告\附件2--car_prices\car_prices.csv"
# 建立连接字符串  
conn_string = f"postgresql://{postgres_user}:{postgres_password}@{postgres_host}:{postgres_port}/{postgres_database}"  
engine = create_engine(conn_string)  

try:  
    # 读取 CSV 文件  
    df = pd.read_csv(csv_file_path)  
    # 将 DataFrame 导入到 PostgreSQL 数据库  
    df.to_sql('car_sales_2', engine, if_exists='append', index=False)  
    print("数据成功导入")  

except Exception as e:  
    print(f"导入数据时出错: {e}")  
finally:  
    # 关闭数据库连接  
    engine.dispose()